﻿//-----------------------------------------------
// RedditSharp (Reddit#)
//
// Copyright (c) 2011 - 2012
// - Angelo Geels <angelo@angelog.nl>
//-----------------------------------------------

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RedditSharp
{
    public class RedditThread
    {
        public RedditPost Post;
        public RedditComment[] Comments;

        /// <summary>
        /// Parses a reddit thread baesd on the ArrayList received.
        /// </summary>
        /// <param name="ThreadData">The thread data in ArrayList form</param>
        /// <returns>The RedditThread</returns>
        public static RedditThread Parse(ArrayList ThreadData)
        {
            RedditThread ret = new RedditThread();

            ret.Post = RedditPost.Parse(ThreadData[0].ToHashtable()["data"].ToHashtable()["children"].ToArrayList()[0].ToHashtable()["data"].ToHashtable());
            ret.Comments = RedditThread.ParseComments(ThreadData[1].ToHashtable()["data"].ToHashtable());

            return ret;
        }

        /// <summary>
        /// Parse comments found in a thread.
        /// </summary>
        /// <param name="commentData">The Hashtable that contains the comments</param>
        /// <returns>Array of the reddit comments</returns>
        public static RedditComment[] ParseComments(Hashtable CommentData)
        {
            List<RedditComment> ret = new List<RedditComment>();

            ArrayList comments = CommentData["children"].ToArrayList();
            foreach (Hashtable comment in comments)
            {
                if ((string)comment["kind"] == "more")
                    continue;

                RedditComment newComment = RedditComment.Parse(comment["data"].ToHashtable());
                ret.Add(newComment);

                object replies = comment["data"].ToHashtable()["replies"];
                if (replies.GetType() == typeof(string))
                    continue;

                newComment.Children = RedditThread.ParseComments(replies.ToHashtable()["data"].ToHashtable());
            }

            return ret.ToArray();
        }
    }
}
